package com.liushuai.demotestcxf.jframe;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.liushuai.demotestcxf.api.InitBillReq;
import com.liushuai.demotestcxf.api.InitBillRsp;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class Demo10 extends JFrame {

    public Demo10() {
        this.setTitle("按钮测试");
        this.setSize(300, 200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setLayout(new FlowLayout());

        JButton button1 = new JButton("按钮1");

        // 传统按钮监听器添加方式
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
                org.apache.cxf.endpoint.Client client = dcf.createClient("http://localhost:8099/test/user?wsdl");
                //getUser 为接口中定义的方法名称  张三为传递的参数   返回一个Object数组
                Object[] objects = new Object[0];
                XmlMapper mapper = new XmlMapper();
                InitBillReq req = new InitBillReq();
                String xmlStr = null;
                try {
                    xmlStr = mapper.writeValueAsString(req);
                    System.out.println(xmlStr);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                try {
                    objects = client.invoke("getUser", xmlStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                InitBillRsp rsp = null;
                try {
                    rsp = mapper.readValue(objects[0].toString(), InitBillRsp.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //输出调用结果
                System.out.println("*****" + objects[0].toString());
                JOptionPane.showMessageDialog(null, "我是按钮1！" + objects[0].toString());
            }
        });
        this.add(button1);

        JButton button2 = new JButton("按钮2");

        // 通过函数接口方式添加按钮监听器，Java8 及以后版本支持
//        button2.addActionListener(e -> {
//            JOptionPane.showMessageDialog(null, "我是按钮2！");
//        });
        this.add(button2);
    }

    public static void main(String[] args) {

        new Demo10().setVisible(true);
    }
}